package com.szholly.data.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.szholly.data.general.RowBase;

/**
 * 定义分页查询
 */
@SuppressWarnings("rawtypes")
public class SplitPageResultSetExtractor<T extends RowBase> implements
		ResultSetExtractor {

	/**
	 * 起始行号
	 */
	private final int startIndex;

	/**
	 * 每页记录数
	 */
	private final int pageSize;
	
	private final boolean refresRowCount;

	/**
	 * 行包装器
	 */
	private final RowBaseMapper<T> rowMapper;
	
	public int rowCount;

	public SplitPageResultSetExtractor(Class<T> c, int startIndex, int pageSize, boolean refresRowCount) {
		this.startIndex = startIndex;
		this.pageSize = pageSize;
		this.rowMapper = new RowBaseMapper<T>(c);
		this.refresRowCount = refresRowCount;
	}

	/**
	 * 处理结果集合,被接口自动调用，该类外边不应该调用
	 */
	public Object extractData(ResultSet rs) throws SQLException,
			DataAccessException {
		List<T> result = new ArrayList<T>();
		rs.first();
		rs.relative(startIndex - 1);
		int count = 0;
		while (rs.next()) {
			count++;
			result.add(rowMapper.mapRow(rs, startIndex + count));
			if (count == pageSize) {
				break;
			}
		}
		if(refresRowCount){
			rs.last();
			rowCount = rs.getRow();
		}
		return result;
	}
}